import tushare as ts
import pandas as pd

# 初始化pro接口
pro = ts.pro_api('276da5751ba9fda134012d591c37d0cbed93bdf1dad172617e265d6a')

# 拉取数据
df = pro.daily(**{
    "ts_code": "605319.SH",
    "trade_date": "",
    "start_date": 20220727,
    "end_date": 20250415,
    "offset": "",
    "limit": ""
}, fields=[
    "ts_code",
    "trade_date",
    "open",
    "high",
    "low",
    "close",
    "pre_close",
    "change",
    "pct_chg",
    "vol",
    "amount"
])

# 将数据按交易日期排序
df['trade_date'] = pd.to_datetime(df['trade_date'])
df = df.sort_values(by='trade_date')
df = df.set_index('trade_date')
print(df)

import pandas as pd
import talib

# 计算移动平均线
df['MA5'] = df['close'].rolling(5).mean()
df['MA10'] = df['close'].rolling(10).mean()

# 计算相对强弱指标RSI
df['RSI'] = talib.RSI(df['close'], timeperiod=12)

# 计算动量指标MOM
df['MOM'] = talib.MOM(df['close'], timeperiod=5)

# 计算指数移动平均值EMA
df['EMA12'] = talib.EMA(df['close'], timeperiod=12)
df['EMA26'] = talib.EMA(df['close'], timeperiod=26)

# 计算异同移动平均线MACD
df['MACD'], df['MACDsignal'], df['MACDhist'] = talib.MACD(df['close'],
    fastperiod=6, slowperiod=12, signalperiod=9)

# 删除缺失值
df.dropna(inplace=True)

# 特征变量
features = ['open', 'high', 'low', 'close', 'MA5', 'MA10', 'RSI', 'MOM', 'EMA12', 'EMA26', 'MACD', 'MACDsignal', 'MACDhist']

# 目标变量：下一天的股价涨跌情况
df['target'] = df['close'].shift(-1) > df['close']
df['target'] = df['target'].astype(int)

# 删除最后一行（因为最后一行的目标变量是NaN）
df = df.dropna()

# 提取特征和目标变量
X = df[features]
y = df['target']

split = int(len(X) * 0.9)
from sklearn.ensemble import RandomForestClassifier

# 构建随机森林模型
model = RandomForestClassifier(n_estimators=100, max_depth=5, random_state=42)
model.fit(X_train, y_train)
import numpy as np
from sklearn.metrics import accuracy_score

# 预测测试集
y_pred = model.predict(X_test)

# 计算准确率
accuracy = accuracy_score(y_test, y_pred)
print(f"模型准确率: {accuracy:.2f}")

# 分析特征重要性
importances = model.feature_importances_
feature_names = X.columns
sorted_indices = np.argsort(importances)[::-1]

print("特征重要性：")
for i in sorted_indices:
    print(f"{feature_names[i]}: {importances[i]:.4f}")
    import matplotlib.pyplot as plt

    # 计算收益率
    X_test['predicted'] = model.predict(X_test)
    X_test['daily_return'] = X_test['close'].pct_change()
    X_test['strategy_return'] = X_test['predicted'].shift(1) * X_test['daily_return']

    # 计算累积收益率
    X_test['cumulative_return'] = (1 + X_test['daily_return']).cumprod()
    X_test['cumulative_strategy_return'] = (1 + X_test['strategy_return']).cumprod()

    # 绘制收益回测曲线
    plt.figure(figsize=(14, 7))
    plt.plot(X_test.index, X_test['cumulative_return'], label='股票实际收益率')
    plt.plot(X_test.index, X_test['cumulative_strategy_return'], label='模型策略收益率')
    plt.legend()
    plt.title('收益回测曲线')
    plt.xlabel('日期')
    plt.ylabel('累积收益率')
    plt.show()